﻿using Microsoft.SqlServer.Types;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace DBCook.Serializes
{
    /// <summary>
    /// 空间数据序列化
    /// </summary>
    public class SqlGeographyConvertor : Newtonsoft.Json.JsonConverter<SqlGeography>
    {
        public override SqlGeography ReadJson(JsonReader reader, Type objectType, [AllowNull] SqlGeography existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, [AllowNull] SqlGeography value, JsonSerializer serializer)
        {
            writer.WriteValue($"geography::STGeomFromText('{value.ToString()}', {value.STSrid.ToString()})");
        }
    }

    /// <summary>
    /// 空间数据序列化
    /// </summary>
    public class SqlGeometryConvertor : Newtonsoft.Json.JsonConverter<SqlGeometry>
    {
        public override SqlGeometry ReadJson(JsonReader reader, Type objectType, [AllowNull] SqlGeometry existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, [AllowNull] SqlGeometry value, JsonSerializer serializer)
        {
            writer.WriteValue($"geometry::STGeomFromText('{value.ToString()}', {value.STSrid.ToString()})");
        }
    }

    /// <summary>
    /// 层次结构数据序列化
    /// </summary>
    public class SqlHierarchyIdConvertor : Newtonsoft.Json.JsonConverter<SqlHierarchyId>
    {
        public override SqlHierarchyId ReadJson(JsonReader reader, Type objectType, [AllowNull] SqlHierarchyId existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, [AllowNull] SqlHierarchyId value, JsonSerializer serializer)
        {
            writer.WriteValue(value.ToString());
        }
    }

    /// <summary>
    /// 字节数组序列化
    /// </summary>
    public class ByteArrayConvertor : Newtonsoft.Json.JsonConverter<byte[]>
    {
        public override byte[] ReadJson(JsonReader reader, Type objectType, [AllowNull] byte[] existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, [AllowNull] byte[] value, JsonSerializer serializer)
        {
            var bs = value;
            var sb = new StringBuilder();
            sb.Append("0x");
            foreach (var by in bs)
            {
                sb.Append(by.ToString("X2"));
            }
            writer.WriteValue(sb.ToString());
        }
    }

}
